package org.sbear;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.sbear.handler.UserServiceHandler;
import org.sbear.pojo.RpcRequest;
import org.sbear.util.JSONSerializer;
import org.sbear.util.RpcDecoder;
import org.sbear.util.RpcEncoder;

public class NettyServer {

    /**
     * 创建一个方法启动服务器
     *
     * @param hostName
     * @param port
     */
    public static void startServer(String hostName, int port) throws Exception {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new StringEncoder());
                        //pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //把我们自顶一个ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        registerService(hostName, port);
        //4.绑定端口
        serverBootstrap.bind(hostName, port).sync();
    }

    private static void registerService(String hostName, int port) throws Exception {

        String serviceAddress = hostName + ":" + port;
        String zookeeperAddress = "192.168.227.129:2181";
        String servicePath = "/service";

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

        CuratorFramework client = CuratorFrameworkFactory
                .builder()
                .retryPolicy(retryPolicy)
                .connectString(zookeeperAddress)
                .sessionTimeoutMs(3000)
                .connectionTimeoutMs(3000)
                .build();
        client.start();

        Stat stat = client.checkExists().forPath(servicePath);
        if (stat == null) {
            client.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(servicePath);
        }
        client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(servicePath + "/" + serviceAddress);
    }
}
